let mqtt = require('mqtt')
let client = {}
export default {
    launch(url) {
        client = mqtt(url, {
            connectTimeout: 10000,
            clean: true,
        })

    },
    message(_topic, callback) {
        client.on('message', (topic, message) => {
            if (_topic === topic) {
                callback(topic, message)
            }
        })
    },
    end() {
        client.end()
    },
    subscribe(topic) {
        client.subscribe(topic, { qos: 0 }, (error) => {
            if (!error) {
              console.log("订阅成功");
            } else {
              console.log("订阅失败");
            }
          });
        console.log('subscribe:', topic)
    },
    publish(topic, message) {
        client.publish(topic, JSON.stringify(message), {
            qos: 0
        })
    },
    publishHex(topic, message) {
        client.publish(topic, message, {
            qos: 0
        })
    }
}